<template>
	<view>
		<u-navbar title="企业注册" autoBack="true" bgColor="transparent" :titleStyle="{fontSize:'36rpx',fontWeight:'500'}">
		</u-navbar>
		<scroll-view class="container" scroll-y="true">
			<view class="registerGroup">
				<u--form ref="form" :model="company" :rules="rules" labelWidth="100">
					<view class="title">
						<text>上传图片</text>
						<text class="desc">（请保证信息清晰可见，照片支持5M以内png、jpg格式）</text>
					</view>
					<image :src="uploadImg" class="uploadImg" @tap="photoSelect"></image>
					<view class="title">
						<text>企业信息</text>
						<text class="desc"></text>
					</view>
					<u-form-item prop="companyName" :borderBottom='false' ref="companyName">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>企业名称</text>
						</template>
						<u-input disabled v-model="company.companyName" placeholder="自动识别" />
					</u-form-item>
					<u-form-item prop="taxID" :borderBottom='false' ref="taxID">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>纳税人识别号</text>
						</template>
						<u-input disabled v-model="company.taxID" placeholder="自动识别" />
					</u-form-item>
					<u-form-item prop="account" :borderBottom='false' ref="account">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>收款账号</text>
						</template>
						<u-input v-model="company.account" placeholder="请输入收款账号" />
					</u-form-item>
					<u-form-item prop="bank" :borderBottom='false' ref="bank">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>*收款银行</text>
						</template>
						<u-input v-model="company.bank" placeholder="请输入收款银行" />
					</u-form-item>
					<u-form-item prop="bankNumber" :borderBottom='false' ref="bankNumber">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>收款银行行号</text>
						</template>
						<u-input v-model="company.bankNumber" placeholder="请输入收款银行行号" />
					</u-form-item>
					<u-form-item prop="name" :borderBottom='false' ref="name">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>联系人</text>
						</template>
						<u-input v-model="company.name" placeholder="请输入联系人" />
					</u-form-item>
					<u-form-item prop="phone" :borderBottom='false' ref="phone">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>联系电话</text>
						</template>
						<u-input v-model="company.phone" placeholder="请输入联系电话" />
					</u-form-item>
					<u-form-item prop="email" :borderBottom='false' ref="email">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>邮箱</text>
						</template>
						<u-input v-model="company.email" placeholder="请输入邮箱" />
					</u-form-item>
				</u--form>
			</view>
		</scroll-view>
		<view class="bottomBtnDiv">
			<view class="bottomBtn">
				<u-button :type="hasIdentify?'primary':'default'" :disabled="hasIdentify?false:true" text="注册"
					@tap="regCompany"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		company_reg
	} from '@/api/user.js'
	export default {
		data() {
			return {
				company: {
					companyName: "",
					taxID: "",
					account: "",
					bank: "",
					bankNumber: "",
					name: "",
					phone: "",
					email: ""
				},
				rules: {
					'companyName': {
						type: 'string',
						required: true,
						message: '请上传营业执照',
						trigger: ['blur', 'change']
					},
					'taxID': {
						type: 'string',
						required: true,
						message: '请上传营业执照',
						trigger: ['blur', 'change']
					},
					'account': {
						type: 'string',
						required: true,
						message: '请填写收款账号',
						trigger: ['blur', 'change']
					},
					'bank': {
						type: 'string',
						required: true,
						message: '请填写收款银行',
						trigger: ['blur', 'change']
					},
					'bankNumber': {
						type: 'string',
						required: true,
						message: '请填写收款银行行号',
						trigger: ['blur', 'change']
					},
					'name': {
						type: 'string',
						required: true,
						message: '请填写联系人',
						trigger: ['blur', 'change']
					},
					'phone': [
						{
							pattern: /^1[3-9]\d{9}$/, // 正则表达式校验
							required: true,
							message: '请输入正确的手机号格式',
							trigger: ['change', 'blur']
						}
					],
					'email': [{
							required: true,
							message: '请输入邮箱地址',
							trigger: ['change', 'blur']
						},
						{
							type: 'email',
							message: '请输入正确的邮箱地址',
							trigger: ['change', 'blur']
						}
					]
				},
				hasIdentify: true,
				uploadImg: "/static/upload_yyzz.png"
			};
		},
		methods: {
			regCompany() {
				this.$refs.form.validate().then((res) => {
					let query = {};
					company_reg(query).then(res => {
						console.log('company_reg', res)
					}).catch(err => {
						console.error('companyReg', err);
					})
				}).catch(errors => {
					// 表单验证失败，errors 是包含所有验证错误的对象
					console.error('验证失败', errors);
				});
			},
			async photoSelect() {
				try {
					const res = await uni.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						extension: ['jpg', 'png'],
					});

					if (res.tempFilePaths.length > 0) {
						const base64 = await this.pathToBase64(res.tempFilePaths[0]);
						this.uploadImg = base64;
						this.recognizeBusinessLicense(base64)
					}
				} catch (err) {
					console.error('选择图片失败：', err);
				}
			},
			pathToBase64(path) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: path,
						encoding: 'base64',
						success: (res) => resolve(`data:image/jpeg;base64,${res.data}`),
						fail: (err) => reject(err)
					});
				});
			},
			async recognizeBusinessLicense(imageBase64) {
				try {
					// 获取 access_token
					const accessToken = await this.getAccessToken();

					// 调用 OCR 业务执照识别接口
					const response = await uni.request({
						url: `https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token=${accessToken}`,
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						data: {
							image: imageBase64 // 图片的 Base64 编码字符串
						}
					});

					const {
						data
					} = response;
					this.company.companyName = data.words_result['单位名称'].words;
					this.company.taxID = data.words_result['社会信用代码'].words;
					console.log('OCR 识别结果:', data, this.company);
					return data;
				} catch (error) {
					console.error('OCR 识别失败:', error);
					throw error;
				}
			},
			async getAccessToken() {
				try {
					const response = await uni.request({
						url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=LMyKI2zWcLzr9x1VnCGowtIA&client_secret=vejkTG4ovyGpjjuRkAFxJ9Vp5Izwq5p0',
						method: 'POST'
					});

					const {
						data
					} = response;
					return data.access_token;
				} catch (error) {
					console.error('获取 access_token 失败:', error);
					throw error;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.title {
		display: flex;
		justify-content: flex-start;
		align-items: flex-end;
		color: #888;
		font-size: 28rpx;

		.desc {
			font-size: 20rpx;
		}
	}

	.uploadImg {
		display: block;
		margin: 56rpx auto;
		width: 320rpx;
		height: 210rpx;
	}

	.container {
		flex-grow: 1;
	}

	.bottomBtnDiv {
		bottom: 60rpx;
		z-index: 1;
	}

	.required-label {
		display: flex;
		align-items: center;
		width: 232rpx;
		font-size: 28rpx;
		font-weight: 400;

		.required-star {
			color: red;
		}
	}
</style>